package com.egg.common.swagger.config;

import com.egg.common.swagger.param.SwaggerParam;
import io.swagger.annotations.ApiModelProperty;
import io.swagger.annotations.ApiOperation;
import lombok.Data;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.ComponentScan;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.Profile;
import springfox.documentation.builders.ApiInfoBuilder;
import springfox.documentation.builders.ParameterBuilder;
import springfox.documentation.builders.PathSelectors;
import springfox.documentation.builders.RequestHandlerSelectors;
import springfox.documentation.schema.ModelRef;
import springfox.documentation.service.ApiInfo;
import springfox.documentation.service.ApiKey;
import springfox.documentation.service.AuthorizationScope;
import springfox.documentation.service.Parameter;
import springfox.documentation.service.SecurityReference;
import springfox.documentation.service.SecurityScheme;
import springfox.documentation.spi.DocumentationType;
import springfox.documentation.spi.service.contexts.SecurityContext;
import springfox.documentation.spring.web.plugins.Docket;
import springfox.documentation.swagger2.annotations.EnableSwagger2;

import java.util.ArrayList;
import java.util.List;

/**
 * @author east
 */
@Profile({"test", "dev", "local"})
@Data
@ComponentScan(basePackages = "com.egg.common.swagger.param")
@EnableSwagger2
@Configuration
@ConfigurationProperties(prefix = "swagger.api")
public class SwaggerConfig {


    @ApiModelProperty(value = "是否开启", notes = "true")
    private Boolean enabled;

    @ApiModelProperty(value = "标题", notes = "xx系统")
    private String title;

    @ApiModelProperty(value = "版本", notes = "系统版本")
    private String version;

    @ApiModelProperty(value = "描述", notes = "这个系统如何如何")
    private String description;


    @Autowired
    private List<SwaggerParam> swaggerParamList;


    @Bean
    public Docket initDocket() {
        return new Docket(DocumentationType.SWAGGER_2)
                .enable(getEnabled())
                // 用来创建该API的基本信息，展示在文档的页面中（自定义展示的信息）
                .apiInfo(apiInfo())
                // 设置哪些接口暴露给Swagger展示
                .select()
                // 扫描所有有注解的api
                .apis(RequestHandlerSelectors.withMethodAnnotation(ApiOperation.class))
                .paths(PathSelectors.any())
                .build()
                // 公共请求头 当公共请求头设置了参与，优先以公共请求头中的值为准
                .securitySchemes(securitySchemes())
                .securityContexts(securityContexts())
                // 私有请求头
                //.globalOperationParameters(parameterList())
                ;
    }

    private List<SecurityScheme> securitySchemes() {
        List<SecurityScheme> apiKeyList = new ArrayList<>();
        swaggerParamList.forEach(o -> {
            apiKeyList.add(new ApiKey(o.getName(), o.getName(), o.getParameterType()));
        });
        return apiKeyList;
    }

    /**
     * 安全上下文
     */
    private List<SecurityContext> securityContexts() {
        List<SecurityContext> securityContexts = new ArrayList<>();
        securityContexts.add(
                SecurityContext.builder()
                        .securityReferences(defaultAuth())
                        .build());
        return securityContexts;
    }

    /**
     * 默认的安全上引用
     */
    private List<SecurityReference> defaultAuth() {
        AuthorizationScope authorizationScope = new AuthorizationScope("global", "accessEverything");
        AuthorizationScope[] authorizationScopes = new AuthorizationScope[1];
        authorizationScopes[0] = authorizationScope;
        List<SecurityReference> securityReferences = new ArrayList<>();
        swaggerParamList.forEach(o -> {
            securityReferences.add(new SecurityReference(o.getName(), authorizationScopes));
        });
        return securityReferences;
    }

    private List<Parameter> globalOperationParameters() {
        List<Parameter> parameterList = new ArrayList<>();
        swaggerParamList.forEach(o -> {
            ParameterBuilder param = new ParameterBuilder();
            param.name(o.getName())
                    .description(o.getDescription())
                    .parameterType(o.getParameterType())
                    .modelRef(new ModelRef(o.getModelRef()))
                    .required(o.getRequired())
                    .defaultValue(o.getDefaultValue())
                    .scalarExample(o.getDefaultValue())
                    .order(o.getParameterIndex())
            ;
            parameterList.add(param.build());
        });
        return parameterList;
    }

    private ApiInfo apiInfo() {
        return new ApiInfoBuilder()
                .title(getTitle())
                .description(getDescription())
                .version(getVersion())
                .build();
    }


}